package com.qf.Servlet;

import com.qf.entity.Book;
import com.qf.entity.Page;
import com.qf.service.BookService;
import com.qf.service.impl.BookServiceImpl;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * @author Wy
 * @version V1.0
 * @Project day41-3
 * @Package ${PACKAGE_NAME}
 * @Description: ${TODO}
 * @Date 2022/5/14 12:50
 */
@WebServlet(name = "BookServlet" ,urlPatterns = "/bookList")
public class BookServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
               response.setContentType("text/html; charset=UTF-8");

        BookService bookService = new BookServiceImpl();
//                List<Book> all = bookService.getAll();
        String pageIndex = request.getParameter("pageIndex");
        if(pageIndex==null){
            pageIndex="1";
        }
        //封装Page分页对象, 第一个参数:当前需要跳转到的页码, 第二个参数:每页显示条数
        Page page= new Page(Integer.parseInt(pageIndex),5);
//分页查询, 查询结果集
        List<Book> allPage = bookService.findAllPage(page);
        //分页查询, 查询总记录数
        int allPageCount = bookService.findAllPageCount();
        //将查询到的总记录数, 存入page分页对象中
        //这个对象就可以获得了总页数
        page.setTotaLCounts(allPageCount);

        //使用jsp来展示书籍列表
//        如果重定向到 jsp页面，需要将数据保存到 session
        //如果使用请求转发，可以将数据保存到 request
      /*  HttpSession session = request.getSession();
        session.setAttribute("page",page);

        response.sendRedirect(request.getContextPath()+"/bookList.jsp");*/
        request.setAttribute("bookList",allPage);

      request.setAttribute("page",page);

       request.setAttribute("pageIndex",pageIndex);

        request.getRequestDispatcher("/bookList.jsp").forward(request,response);


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                doPost(request,response);
    }
}
